package com.discuss.community.config;

import com.discuss.community.util.CommunityConstant;
import com.discuss.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略对静态资源的拦截
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
                        "user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/like",
                        "/follow",
                        "/unfollow",
                        "/notice/**"
                ).
                hasAnyAuthority(
                        AUTHORITY_ADMIN,
                        AUTHORITY_MODERATOR,
                        AUTHORITY_USER
                )
                // 除了上面的路径，其他都可以直接访问
                .anyRequest().permitAll()
                // 禁用 csrf 检查
                .and().csrf().disable();

        // 权限不够时处理
        http.exceptionHandling()
                // 没有登录
                .authenticationEntryPoint( (request, response, authenticationException) -> {
                    String xRequestedWith = request.getHeader("x-requested-with");
                    if ("XMLHttpRequest".equals(xRequestedWith)) {
                        // 异步请求  application/plain 表示普通的字符串
                        response.setContentType("application/plain;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        writer.write(CommunityUtil.getJsonString(403, "你还没有登录哦"));
                    } else {
                        // 同步请求
                        response.sendRedirect(request.getContextPath() + "/login");
                    }
                })
                // 权限不足
                .accessDeniedHandler( (request, response, authenticationException) -> {
                    String xRequestedWith = request.getHeader("x-requested-with");
                    if ("XMLHttpRequest".equals(xRequestedWith)) {
                        response.setContentType("application/plain;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        writer.write(CommunityUtil.getJsonString(403, "你没有访问此功能的权限"));
                    } else {
                        response.sendRedirect(request.getContextPath() + "/denied");
                    }
                });

        // Security 底层默认会拦截 /logout 请求, 进行退出处理
        // 覆盖它默认的处理逻辑，才能执行自己的退出代码
        // 修改 SpringSecurity 处理登出的路径，这样SpringSecurity 就不会拦截我们自己写的 /logout 请求
        http.logout().logoutUrl("/securityLogout");
    }
}
